<?php

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------
namespace Home\Controller;
use Think\Controller;

class UnionPayController extends Controller {

    //put your code here
    public function doPay() {
        vendor('UnionPayMobile.common');
        vendor('UnionPayMobile.SDKConfig');
        vendor('UnionPayMobile.secureUtil');
        vendor('UnionPayMobile.PhpLog');
        $log = new \PhpLog(SDK_LOG_FILE_PATH, "PRC", SDK_LOG_LEVEL);
        $log->LogInfo("============处理前台请求开始===============");
        $orderNum = I('id');
       //在此之前goods1的业务订单已经生成，状态为等待支付
        $map['pay_sn'] = $orderNum;
        $order = M('order')->where($map)->count();
        //单个支付和合并支付
        if ($order == 1) {
            //循环获取订单的总价格和商品
            $orders = M('order')->where('pay_sn=%s', array($orderNum))->find();
            //获取订单下的商品
            $orderGoods = M('order_goods')->where('order_id=%s', array($orders['order_id']))->select();
            foreach ($orderGoods as $key => $value) {
                $title .= $value['goods_title'] . '；';
            }
            $title = "共" . count($orderGoods) . "件商品：" . sub_str($title, 0, 22);
            $payPrice = $orders['goods_amount'];
        } else {
            $orders = M('order')->where('pay_sn=%s', array($orderNum))->select();
            foreach ($orders as $key => $value) {
                $payPrice += $value['goods_amount'];
            }
            $title = "合并支付丨" . $order . "笔订单";
        }
        
        //获取平台的优惠券的信息
        $map['pay_sn'] = $orderNum;
        $map['voucher_store'] = 0;
        $tddList = M('order_voucher')->where($map)->select();
        if(!empty($tddList)){
            foreach ($tddList as $key => $value) {
                $totalTdd += $value['voucher_price'];
            }
            $payPrice = $payPrice-$totalTdd;
        }
        
        if (empty($orders)) {
            $this->error('此订单不存在请确认是否有此订单！', USERS_URL . U('/Order/index'));
        }
        if ($orders['order_state'] == 20) {
            $this->error('此订单已经支付成功，不需要在次支付！', USERS_URL . U('/Order/index'));
        }
        
        //生成本地记录数据
        M("orderPay")->add(array(
            'id' => time().rand(1000,9999),
            'pay_sn' =>$orderNum,
            'total' => $payPrice,
            'user_id' => session('user_id'),
            'title' => $title,
            'paytype' => 'UNIONPAY',
            'callback' => SDK_BACK_NOTIFY_URL,
            'url' => SDK_FRONT_NOTIFY_URL,
            'created' => time()
        ));

        // 初始化日志
        $params = array(
            'version' => '5.0.0', //版本号
            'encoding' => 'utf-8', //编码方式
            'certId' => getSignCertId(), //证书ID
            'txnType' => '01', //交易类型  
            'txnSubType' => '01', //交易子类
            'bizType' => '000201', //业务类型
            'frontUrl' => SDK_FRONT_NOTIFY_URL, //前台通知地址
            'backUrl' => SDK_BACK_NOTIFY_URL, //后台通知地址    
            'signMethod' => '01', //签名方法
            'channelType' => '08', //渠道类型，07-PC，08-手机
            'accessType' => '0', //接入类型
            'merId' => '898410153111052', //商户代码，请改自己的商户号
            'orderId' => $orderNum, //商户订单号
            'txnTime' => date('YmdHis'), //订单发送时间
            'txnAmt' => 0.1*100, //交易金额，单位分
            'currencyCode' => '156', //交易币种
            'defaultPayType' => '0001', //默认支付方式    
            //'orderDesc' => '订单描述',  //订单描述，网关支付和wap支付暂时不起作用
            'reqReserved' => ' 淘嘟嘟商城', //请求方保留域，透传字段，查询、通知、对账文件中均会原样出现
        );
        // 签名
        sign($params);
        // 前台请求地址
        $front_uri = SDK_FRONT_TRANS_URL;
        $log->LogInfo("前台请求地址为>" . $front_uri);
        // 构造 自动提交的表单
        $html_form = create_html($params, $front_uri);

        $log->LogInfo("-------前台交易自动提交表单>--begin----");
        $log->LogInfo($html_form);
        $log->LogInfo("-------前台交易自动提交表单>--end-------");
        $log->LogInfo("============处理前台请求 结束===========");
        echo $html_form;
    }

    /*     * ****************************
      服务器同步通知页面方法
      其实这里就是将notify_url.php文件中的代码复制过来进行处理

     * ***************************** */
    function createNote() {
        vendor('UnionPayMobile.common');
        vendor('UnionPayMobile.SDKConfig');
        vendor('UnionPayMobile.secureUtil');
        vendor('UnionPayMobile.PhpLog');
        $log = new \PhpLog(SDK_LOG_FILE_PATH, "PRC", SDK_LOG_LEVEL);
        if (isset($_POST ['signature'])) {
            if (verify($_POST)) {
                $orderId = $_POST ['orderId'];
                //验证成功，改变订单状态
                $payinfo = M("orderPay")->where(array('pay_sn' => $orderId))->find();
                if ($payinfo['status'] == 10 && !empty($payinfo['callback'])) {
                    //修改支付订单的状态
                    $data['result'] = serialize($_POST);
                    $data['trade_no'] = $_POST['queryId'];
                    $data['buyer_email'] = $_POST['traceNo'];
                    $data['payment'] = $_POST['txnAmt'];
                    $data['pay_time'] = time();
                    $data['status'] = 20;
                    M("orderPay")->where(array('pay_sn' => $orderId))->save($data);

                    //订单结算
                    $map['pay_sn'] = $payinfo['pay_sn'];
                    $oModel = D('Order');
                    $oList = $oModel->relation('OrderGoods')->where($map)->select();
                    //获取平台的优惠券的信息
                    $maps['pay_sn'] = $payinfo['pay_sn'];
                    $maps['voucher_store'] = 0;
                    $tddList = M('order_voucher')->where($maps)->select();
                    if (!empty($tddList)) {
                        foreach ($tddList as $key => $value) {
                            $totalTdd += $value['voucher_price'];
                        }
                    }
                    $bili = (1 - $totalTdd/($payinfo['total']+$totalTdd)); //平台优惠比例
                    foreach ($oList as $key => $value) {
                        if ($value['discount_fee'] > 0) {
                            foreach ($value['OrderGoods'] as $k => $v) {
                                $pay_price[$k] = $bili * $v['goods_price'] * $v['goods_num'];
                                $trader_price += $bili * $v['goods_price'] * $v['goods_num'];
                            }
                            $bili2 = (1 - ($value['discount_fee']/$trader_price));
                            //根据占比更新单个商品时间支付的价格
                            foreach ($value['OrderGoods'] as $k => $v) {
                                //更新实际支付的价格
                                $pay[$k] = $bili2 * $pay_price[$k];
                                //在根据店铺的优惠比例继续计算实际支付的价格
                                M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay[$k]));
                                $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                            }
                            //更新订单的价格及状态
                            M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                        } else {
                            //根据占比更新单个商品时间支付的价格
                            foreach ($value['OrderGoods'] as $k => $v) {
                                //更新实际支付的价格
                                $pay_price[$k] = $bili * $v['goods_price']*$v['goods_num'];
                                M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay_price[$k]));
                                $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                            }
                            //更新订单的价格及状态
                            M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                        }
                    }
                }
            }
        } else {
            echo '签名为空';
        }
        if(isMobile()){
            $this->redirect(WEIXIN_URL.'Order/waitSend');
        }else{
            $this->redirect(HOME_URL.'Order/waitSend');
        }
    }

    /*     * ****************************
      服务器异步通知页面方法
      其实这里就是将notify_url.php文件中的代码复制过来进行处理

     * ***************************** */

    function sureNote(){
        vendor('UnionPayMobile.common');
        vendor('UnionPayMobile.SDKConfig');
        vendor('UnionPayMobile.secureUtil');
        vendor('UnionPayMobile.PhpLog');
        $log = new \PhpLog(SDK_LOG_FILE_PATH, "PRC", SDK_LOG_LEVEL);
        foreach ($_POST as $key => $val) {
            P(isset($mpi_arr[$key]) ? $mpi_arr[$key] : $key);
            P($val);
        }
        if (isset($_POST ['signature'])) {
            
            //P(verify($_POST) ? '验签成功' : '验签失败');
            if (verify($_POST)){
            //验证成功，改变订单状态
                $orderId = $_POST ['orderId'];
                //验证成功，改变订单状态
                $payinfo = M("orderPay")->where(array('pay_sn' => $orderId))->find();
                if ($payinfo['status'] == 10 && !empty($payinfo['callback'])) {
                    //修改支付订单的状态
                    $data['result'] = serialize($_POST);
                    $data['trade_no'] = $_POST['queryId'];
                    $data['buyer_email'] = $_POST['traceNo'];
                    $data['payment'] = $_POST['txnAmt'];
                    $data['pay_time'] = time();
                    $data['status'] = 20;
                    M("orderPay")->where(array('pay_sn' => $orderId))->save($data);

                    //订单结算
                    $map['pay_sn'] = $payinfo['pay_sn'];
                    $oModel = D('Order');
                    $oList = $oModel->relation('OrderGoods')->where($map)->select();
                    //获取平台的优惠券的信息
                    $maps['pay_sn'] = $payinfo['pay_sn'];
                    $maps['voucher_store'] = 0;
                    $tddList = M('order_voucher')->where($maps)->select();
                    if (!empty($tddList)) {
                        foreach ($tddList as $key => $value) {
                            $totalTdd += $value['voucher_price'];
                        }
                    }
                    $bili = (1 - $totalTdd/($payinfo['total']+$totalTdd)); //平台优惠比例
                    foreach ($oList as $key => $value) {
                        if ($value['discount_fee'] > 0) {
                            foreach ($value['OrderGoods'] as $k => $v) {
                                $pay_price[$k] = $bili * $v['goods_price'] * $v['goods_num'];
                                $trader_price += $bili * $v['goods_price'] * $v['goods_num'];
                            }
                            $bili2 = (1 - ($value['discount_fee']/$trader_price));
                            //根据占比更新单个商品时间支付的价格
                            foreach ($value['OrderGoods'] as $k => $v) {
                                //更新实际支付的价格
                                $pay[$k] = $bili2 * $pay_price[$k];
                                //在根据店铺的优惠比例继续计算实际支付的价格
                                M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay[$k]));
                                $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                            }
                            //更新订单的价格及状态
                            M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                        } else {
                            //根据占比更新单个商品时间支付的价格
                            foreach ($value['OrderGoods'] as $k => $v) {
                                //更新实际支付的价格
                                $pay_price[$k] = $bili * $v['goods_price']*$v['goods_num'];
                                M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay_price[$k]));
                                $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                            }
                            //更新订单的价格及状态
                            M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                        }
                    }
                }
            }else{
                echo '签名错误';
            }
        } else {
            echo '签名为空';
        }
    }

}
